package com.jack.lib.base

import android.os.Bundle
import android.view.*
import androidx.fragment.app.DialogFragment
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.ReflectUtils
import com.jack.lib.core.ext.arguments

/**
 * author : chong.huang
 * create : 2022/1/6
 * desc   :
 */
abstract class BaseDialogFragment<VB: ViewBinding> : DialogFragment() {

    var isInitialize = false
    protected lateinit var binding: VB


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_FRAME, R.style.BaseDialog)
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = ReflectUtils.reflect(arguments(0)).method("inflate", inflater, container, false).get()
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        isInitialize = true

        dialog?.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        dialog?.setCanceledOnTouchOutside(true)

        initLayout()
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.also {
            val lp = it.attributes
            lp.width = getWidth()
            lp.height = getHeight()
            lp.gravity = getGravity()
            lp.dimAmount = 1 - getAlpha()
            lp.flags = lp.flags or WindowManager.LayoutParams.FLAG_DIM_BEHIND
            it.attributes = lp
            it.setWindowAnimations(getWindowAnim())
        }
    }

    open fun getWidth() = WindowManager.LayoutParams.MATCH_PARENT

    open fun getHeight() = WindowManager.LayoutParams.WRAP_CONTENT

    open fun getGravity(): Int = Gravity.CENTER

    open fun getAlpha(): Float = 0.4f

    open fun getWindowAnim(): Int = 0

    abstract fun initLayout()
}